package com.tanhua.server.service;

import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.SoulTestApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SoulTestService {
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private SoulTestApi soulTestApi;
    public ResponseEntity findSoulTestList() {
        Long userId = UserHolder.getUserId();
        List<SoulTest> soulTestList = soulTestApi.findSoulTestList(userId);
        List<SoulTestVo> voList = new ArrayList<>();
        for (SoulTest soulTest : soulTestList) {
            SoulTestVo vo = new SoulTestVo();
            BeanUtils.copyProperties(soulTest,vo);
            vo.setId(soulTest.getSid());
            vo.setQuestions(findQuestionVoList(soulTest.getSid()));
            voList.add(vo);
        }
        soulTestApi.saveSoulTestUser(userId);
        return ResponseEntity.ok(voList);
    }
    //根据sid查询试题表
    public List<SoulTestQuestionVo> findQuestionVoList(String sid){
        List<SoulTestQuestion> questions = soulTestApi.findQuestionList(sid);
        List<SoulTestQuestionVo> questionVos = new ArrayList<>();
        for (SoulTestQuestion question : questions) {
            SoulTestQuestionVo vo = new SoulTestQuestionVo();
            vo.setId(question.getQid());
            vo.setQuestion(question.getQuestion());
            vo.setOptions(findOptionsVos(question.getQid(),sid));
            questionVos.add(vo);
        }
        return questionVos;
    }
    //根据qid查询选项列表
    public List<OptionsVo> findOptionsVos(String questionQid, String sid){
        List<Option> options = soulTestApi.findOptions(questionQid,sid);
        List<OptionsVo> optionsVoList = new ArrayList<>();
        for (Option option : options) {
            OptionsVo vo = new OptionsVo();
            vo.setId(option.getOid());
            vo.setOption(option.getOption());
            optionsVoList.add(vo);
        }
        return optionsVoList;
    }

    public ResponseEntity submitQuestion(Long userId, List<Map> idList) {
        List<RecordQuestion> recordQuestions = new ArrayList<>();
        for (int i = 0; i < idList.size(); i++) {
            Map map = idList.get(i);
            String qid = (String) map.get("questionId");
            String oid = (String) map.get("optionId");

            //封装每条问题的分数
            RecordQuestion recordQuestion = new RecordQuestion();
            recordQuestion.setId(ObjectId.get());
            recordQuestion.setUserId(userId);
            SoulTestQuestion soulTestQuestion = soulTestApi.findQid(qid);
            String sid = soulTestQuestion.getSid();
            recordQuestion.setSid(sid);
            Option option = soulTestApi.findOid(oid);
            Integer score = option.getScore();
            recordQuestion.setScore(score);
            RecordQuestion recordQuestion1 = soulTestApi.saveRecordQuestion(recordQuestion);
            recordQuestions.add(recordQuestion1);
        }

        Integer countScore = 0;
        for (RecordQuestion recordQuestion : recordQuestions) {
//            sid = recordQuestion.getSid();
            countScore += recordQuestion.getScore();
        }
        Option option = null;
        for (int i = 0; i < idList.size(); i++) {
            Map map = idList.get(i);
            String qid = (String) map.get("questionId");
            String oid = (String) map.get("optionId");
            String sid = null;
            option = soulTestApi.findOptionByOqId(qid,oid);
        }
        String sid = option.getSid();

        //获取报告表数据，如果没有就新增如果有就增加分数
        RecordReport recordReport = soulTestApi.findCountScore(userId,sid);
        if (recordReport == null){
            recordReport = new RecordReport();
            recordReport.setId(ObjectId.get());
            //初级报告id：1，中级报告id：2，高级报告id：3
            recordReport.setReportId(sid);
            recordReport.setUserId(userId);
            recordReport.setSid(sid);
            recordReport.setCountScore(countScore);
            soulTestApi.saveRecordReport(recordReport);
            //增加报告表后修改问卷表增加rid
            soulTestApi.updateReportId(recordReport.getReportId(),userId,sid);
            //增加报告表后修改下一级的状态
            if (!sid.equals("3")){
                Integer sidI = Integer.valueOf(sid);
                String sidPlus =String.valueOf(sidI + 1);
                SoulTest soulTest = soulTestApi.findNextLevelByUidAndSid(userId,sidPlus);
                Integer isLock = soulTest.getIsLock();
                if (isLock == 1){
                    soulTestApi.updateSoulTestIsLock(userId,sidPlus);
                }
            }
        }else{
            soulTestApi.updateRecordReport(recordReport,countScore);
            //修改报告表后修改问卷表增加rid
            soulTestApi.updateReportId(recordReport.getReportId(),userId,sid);
            if (!sid.equals("3")){
                Integer sidI = Integer.valueOf(sid);
                String sidPlus =String.valueOf(sidI + 1);
                SoulTest soulTest = soulTestApi.findNextLevelByUidAndSid(userId,sidPlus);
                Integer isLock = soulTest.getIsLock();
                if (isLock == 1){
                    soulTestApi.updateSoulTestIsLock(userId,sidPlus);
                }
            }
        }
        return ResponseEntity.ok(recordReport.getReportId());
    }

    public ResponseEntity findReport(String reportId) {
        RecordReport recordReport = soulTestApi.findByRid(reportId);
        Integer countScore = recordReport.getCountScore();
        ScoringReportVo scoringReportVo = new ScoringReportVo();
        if (countScore < 21){
            ScoringReport scoringReport = soulTestApi.findByCountRid("1");
            List<String> dimensions = scoringReport.getDimensionList();
            List<ReportMap> reportMapList = new ArrayList<>();
            for (String dimension : dimensions) {
                ReportMap reportMap = new ReportMap();
                String[] dim = dimension.split(",");
                reportMap.setKey(dim[0]);
                reportMap.setValue(dim[1]);
                reportMapList.add(reportMap);
            }
            scoringReportVo.setDimensions(reportMapList);
            BeanUtils.copyProperties(scoringReport,scoringReportVo);
        }else if (countScore >= 21 && countScore <=40){
            ScoringReport scoringReport = soulTestApi.findByCountRid("2");
            List<String> dimensions = scoringReport.getDimensionList();
            List<ReportMap> reportMapList = new ArrayList<>();
            for (String dimension : dimensions) {
                ReportMap reportMap = new ReportMap();
                String[] dim = dimension.split(",");
                reportMap.setKey(dim[0]);
                reportMap.setValue(dim[1]);
                reportMapList.add(reportMap);
            }
            scoringReportVo.setDimensions(reportMapList);
            BeanUtils.copyProperties(scoringReport,scoringReportVo);
        }else if (countScore >= 41 && countScore <= 55){
            ScoringReport scoringReport = soulTestApi.findByCountRid("3");
            List<String> dimensions = scoringReport.getDimensionList();
            List<ReportMap> reportMapList = new ArrayList<>();
            for (String dimension : dimensions) {
                ReportMap reportMap = new ReportMap();
                String[] dim = dimension.split(",");
                reportMap.setKey(dim[0]);
                reportMap.setValue(dim[1]);
                reportMapList.add(reportMap);
            }
            scoringReportVo.setDimensions(reportMapList);
            BeanUtils.copyProperties(scoringReport,scoringReportVo);
        }else if (countScore <= 56){
            ScoringReport scoringReport = soulTestApi.findByCountRid("4");
            List<String> dimensions = scoringReport.getDimensionList();
            List<ReportMap> reportMapList = new ArrayList<>();
            for (String dimension : dimensions) {
                ReportMap reportMap = new ReportMap();
                String[] dim = dimension.split(",");
                reportMap.setKey(dim[0]);
                reportMap.setValue(dim[1]);
                reportMapList.add(reportMap);
            }
            scoringReportVo.setDimensions(reportMapList);
            BeanUtils.copyProperties(scoringReport,scoringReportVo);
        }
        List<UserInfo> userInfoList = userInfoApi.randomInfo(4);
        List<UserInfoLow> userInfoLows = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserInfoLow userInfoLow = new UserInfoLow();
            userInfoLow.setId(userInfo.getId().intValue());
            userInfoLow.setAvatar(userInfo.getAvatar());
            userInfoLows.add(userInfoLow);
        }
        scoringReportVo.setSimilarYou(userInfoLows);
        return ResponseEntity.ok(scoringReportVo);
    }
}
